package logic

import (
	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"
	"cloud-disk/xorm"
	"context"
	"github.com/zeromicro/go-zero/core/logx"
)

type ShareBasicDetailLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewShareBasicDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShareBasicDetailLogic {
	return &ShareBasicDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ShareBasicDetailLogic) ShareBasicDetail(req *types.ShareBasicDetailRequest, userIdentity string) (resp *types.ShareBasicDetailResponse, err error) {
	resp = new(types.ShareBasicDetailResponse)
	sb, has, err := l.svcCtx.ShareBasicModel.GetShareBasic(req.Identity)
	if err != nil {
		resp.Message = "获取失败" + err.Error()
		resp.Code = 100
		return resp, nil
	}
	if !has {
		resp.Message = "获取失败,记录不存在"
		resp.Code = 100
		return resp, nil
	}

	// 对分享记录加一
	_, err = xorm.Xorm.Exec("update share_basic set click_num = click_num +1 where identity = ?", req.Identity)
	if err != nil {
		resp.Message = "获取失败 " + err.Error()
		resp.Code = 100
		return resp, nil
	}
	rep, has, err := l.svcCtx.RepositoryPoolModel.GetRepositoryPoolByIdentity(sb.RepositoryIdentity)
	if err != nil {
		resp.Message = "获取失败" + err.Error()
		resp.Code = 100
		return resp, nil
	}

	if !has {
		resp.Message = "资料记录不存在"
		resp.Code = 100
		return resp, nil
	}

	ur, has, err := l.svcCtx.UserRepostioryModel.GetFileByIdentity(sb.UserRepositoryIdentity)
	if err != nil {
		resp.Message = "获取失败" + err.Error()
		resp.Code = 100
		return resp, nil
	}
	if !has {
		resp.Message = "记录不存在"
		resp.Code = 100
		return resp, nil
	}
	item := types.ShareItem{
		RepositoryIdentity: sb.RepositoryIdentity,
		Name:               ur.Name,
		Ext:                ur.Ext,
		Size:               int64(rep.Size),
		Path:               rep.Path,
	}

	resp.Data = item
	resp.Message = "获取成功"
	resp.Code = 200
	return resp, nil
}
